import io
import time
import requests
from django.http import JsonResponse, FileResponse, StreamingHttpResponse, HttpResponse
from django.views.generic import View
from django.utils import timezone
from django.db.models import Q
from app.models import *
from django.forms import model_to_dict
from django.core.cache import cache
import pandas as pd
from app.RoleMethod.PublicMethod import PublicMethod
import json
import base64
import re
import os
from wsgiref.util import FileWrapper
from jhcoj_api import settings
import mimetypes
publicMethod = PublicMethod()

# 将数据库查询的Object数据转为json类型数据方法
def changeToJson(data):
    json_list = []
    for i in data:
        json_dict = model_to_dict(i)
        json_list.append(json_dict)
    return json_list


class CoursePower(View):
    def get(self, request):
        # true teacher false student
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_id = request.GET.get("course_id")
        if course_id=="NaN":
            course_id=None
        is_teacher = CourseUser.objects.filter(course_id=course_id, course_user=user_id)
        if is_teacher:
            identity = True
        else:
            identity = False
        return JsonResponse({"status": True, "message": identity})


class MyTasks(View):
    """
    模块：查看个人作业/考试
    接口信息：
        GET：
            token：token认证
            user_id:用户账号
            type: 分辨作业/考试
            done: 分辨是否完成
        POST：
            massage:结果列表
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        task_type = request.GET.get("task_type")
        total = request.GET.get("total")
        page = request.GET.get("page")
        key = request.GET.get("key")
        course_id = request.GET.get("course_id")
        class_id = request.GET.get("class_id")
        print("task_type", task_type, "total", total, "page", page,
              "key", key, "course_id", course_id, "class_id", class_id)
        if not user_id:
            return JsonResponse({'status': False, 'message': '用户未登录'})
        if not total:
            total = '0'
        task_data = []
        identity = User.objects.filter(user_id=user_id).first().user_power
        all_task = TaskUser.objects.all()
        all_course = Course.objects.all()
        if identity < 4:

            all_task = TaskUser.objects.filter(task_creator=user_id, task_course=course_id, task_type=task_type)
            for myTask in all_task:
                task_data.append({
                    "release_id": myTask.release_id,
                    "task_id": myTask.task_id,
                    "task_class": myTask.task_class,
                    "task_user": myTask.task_user,
                    "task_name": myTask.task_name,
                    "course_name": all_course.get(course_id=myTask.task_course).course_name,
                    "begin_time": myTask.begin_time,
                    "end_time": myTask.end_time,
                    "task_type": myTask.task_type,
                    "task_status": key,
                })
            member = all_task.count()
            return JsonResponse({"status": True, "message": task_data, "total": member, "identity": identity})
        my_all_class = ClassUser.objects.filter(user_id=user_id).values_list("class_id", flat=True)
        has_done_task = TaskSubmit.objects.all()
        my_tasks = all_task.filter(Q(task_user=user_id) | Q(task_class__in=my_all_class))

        if task_type >= '0' and task_type <= '2':
            # 0 作业 2 考试
            my_tasks = my_tasks.filter(task_type=task_type)
        my_tasks_list = has_done_task.filter(task_user=user_id).values_list("task_id", flat=True)
        print("my_tasks_list", my_tasks_list)
        if not key:
            key = '0'
        # 找到我提交的任务记录
        # print(type(key))
        if key == "1":
            # key的值 0 全部 1 未完成 2 已完成 3 已过期
            # my_tasks = my_tasks.exclude(task_id__in=my_tasks_list).filter(task_user=user_id)
            my_tasks = my_tasks.exclude(task_id__in=my_tasks_list)
        elif key == "2":
            my_tasks = my_tasks.filter(task_id__in=my_tasks_list)
        elif key == "3":
            my_tasks = my_tasks.filter(end_time__lt=timezone.now()).exclude(task_id__in=my_tasks_list)

        my_tasks.filter(task_creator=course_id)
        if total != '0':
            my_tasks = my_tasks[(int(page) - 1) * int(total): int(page) * int(total)]
        for myTask in my_tasks:
            done_task = has_done_task.filter(release_id=myTask.release_id)
            if done_task:
                key = 2
            elif (not done_task) and (myTask.end_time > timezone.now()):
                key = 1
            elif (not done_task) and (myTask.end_time < timezone.now()):
                key = 3
            else:
                key = None
            task_data.append({
                "release_id": myTask.release_id,
                "task_id": myTask.task_id,
                "task_name": myTask.task_name,
                "course_name": all_course.get(course_id=myTask.task_course).course_name,
                "begin_time": myTask.begin_time,
                "end_time": myTask.end_time,
                "task_type": myTask.task_type,
                "task_status": key,
            })
            print(myTask.task_name, key)
        member = my_tasks.count()
        return JsonResponse({"status": True, "message": task_data, "total": member, "identity": identity})

class CourseAllTask(View):
    """
    模块:
        查看课程下所有的task，以及task发布
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        identity = User.objects.filter(user_id=user_id).first().user_power
        course_id = request.GET.get("course_id")
        page = request.GET.get("page")
        total = request.GET.get("total")
        key = request.GET.get("key")
        text = request.GET.get("text")
        print(course_id, page, total, key, text)
        all_tasks = Task.objects.filter(task_course=course_id)
        if not key:
            key = '4'
        if key >= '0' and key <= '2':
            all_tasks = all_tasks.filter(task_type=key)
        if not total:
            total = '0'
        if total != '0':
            all_tasks = all_tasks[(int(page) - 1) * int(total): int(page) * int(total)]
        task_data = []
        for task in all_tasks:
            task_data.append({
                "task_id": task.task_id,
                "task_name": task.task_title,
                "task_explain": task.task_explain,
                "task_creator": task.creator_name,
                "create_time": task.create_time,
                "total_score": task.total_score,
                "task_type": task.task_type,
                "task_status": key,
                "task_chapter": task.task_chapter,
                "identity": identity
            })
        member = all_tasks.count()
        return JsonResponse({"status": True, "message": task_data, "total": member})

    def post(self, requset):
        token = requset.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        user = User.objects.filter(user_id=user_id).first()
        print(requset.POST)
        course_id = requset.POST.get("course_id")
        task_id = requset.POST.get("task_id")
        task_name = requset.POST.get("title")
        task_class = requset.POST.get("class_lists")
        task_time = requset.POST.get("time")
        task_judge = requset.POST.get("task_judge")
        answer_time = requset.POST.get("time_min")
        task_type = requset.POST.get("task_type")
        print(course_id, task_id, task_name,
              task_class, task_time, type(task_time), task_judge, task_type, answer_time)
        if not task_class:
            return JsonResponse({"status": False, "message": "没有添加班级"})
        task_time = task_time.split(',')
        task_class = task_class.split(',')
        if task_judge == 'true':
            task_judge = 1
        elif task_judge == "false":
            task_judge = 0
        else:
            return JsonResponse({"status": False, "message": "没有特判"})
        tasks = TaskUser.objects.filter(task_id=task_id, task_course=course_id)
        for class_id in task_class:
            task = tasks.filter(task_class=class_id).first()
            if task:
                if task_id:
                    task.task_id = task_id
                if task_name:
                    task.task_name = task_name
                if course_id:
                    task.task_course = course_id
                if task_time[0]:
                    task.begin_time = task_time[0]
                if task_time[1]:
                    task.end_time = task_time[1]
                if task_judge:
                    task.task_judge = task_judge
                if answer_time:
                    task.answer_time = answer_time
                if task_type:
                    task.task_type = task_type
                task.save()

            TaskUser.objects.create(
                task_id=task_id,
                task_name=task_name,
                task_class=class_id,
                task_course=course_id,
                begin_time=task_time[0],
                end_time=task_time[1],
                task_creator=user_id,
                creator_name=user.user_nick,
                task_status=1,
                task_judge=task_judge,
                answer_time=answer_time,
                task_type=task_type,
            )
        # tasks.exclude(Q(task_class__in=task_class)).delete()
        return JsonResponse({"status": True, "message": "发布成功"})

    def delete(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户认证失败"})
        identity = User.objects.filter(user_id=user_id).first().user_power
        if identity > 2:
            return JsonResponse({"status": False, "message": "你没有这个权限"})
        task_id = request.GET.get("task_id")
        course_id = request.GET.get("course_id")
        task_type = request.GET.get("task_type")
        release_id = request.GET.get("release_id")
        print(task_id, course_id, task_type, release_id)
        if release_id:
            TaskUser.objects.filter(release_id=release_id).delete()
            TaskSubmit.objects.filter(release_id=release_id).delete()
        else:
            Task.objects.filter(task_id=task_id).delete()
            TaskQuestion.objects.filter(task_id=task_id).delete()
        return JsonResponse({"status": True, "message": "删除成功"})



class CourseHome(View):
    def get(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        page = request.GET.get('page')
        total = request.GET.get('total')
        sort_by = request.GET.get('sort_by')
        key = request.GET.get('key')
        text = request.GET.get('text')
        subject = request.GET.get('subject')
        me = request.GET.get('me')

        courses = Course.objects.filter(is_show=1)
        if sort_by:
            if sort_by == 'recommend':
                courses = courses.filter(is_recommend=1)
            elif sort_by == 'time':
                courses = courses.order_by('create_time')
            elif sort_by == 'like':
                courses = courses.order_by('course_browse')
            else:
                return JsonResponse({'status': False, 'message': '排序方式错误'})
        if subject:
            courses = courses.filter(Q(course_tags__contains=subject))
        if key:
            if key == 'not_started':
                courses = courses.filter(Q(start_time__gt=timezone.now()))
            elif key == 'started':
                courses = courses.filter(Q(start_time__lt=timezone.now()) & Q(end_time__gt=timezone.now()))
            elif key == 'end':
                courses = courses.filter(Q(end_time__lt=timezone.now()))
        if me:
            if not user_id:
                return JsonResponse({'status': False, 'message': '未登录'})
            my_course = ClassUser.objects.filter(user_id=user_id).values_list('course_id')
            course_list = []
            for course in my_course:
                if course[0] != '' and course[0] is not None:
                    course_list.append(course[0])
            course_list = list(set(course_list))
            courses = courses.filter(Q(course_id__in=course_list))
        if text:
            courses = courses.filter(Q(course_name__contains=text))
        course_num = courses.count()
        if total != '0':
            courses = courses[(int(page) - 1) * int(total): int(page) * int(total)]
        course_data = []
        for item in courses:
            course_data.append(
                {
                    'course_id': item.course_id,
                    'course_name': item.course_name,
                    'course_introduce': item.course_introduce,
                    'course_tags': item.course_tags,
                    'course_cover': item.course_cover,
                    'create_time': item.create_time,
                    'course_cost': item.course_cost,
                    'course_creator': item.course_creator,
                    'creator_name': item.creator_name,
                    'course_status': item.course_status,
                    'start_time': item.start_time,
                    'end_time': item.end_time,
                    'course_browse': item.course_browse,
                    'course_peoples': item.course_peoples,
                    'is_recommend': item.is_recommend,
                }
            )
        return JsonResponse({'status': 'Ture', 'message': course_data, 'total': course_num})


class GetCourseTag(View):
    def get(self, request):
        tags = Course.objects.all().values_list('course_tags').distinct()
        tag_list = []
        for tag in tags:
            if not tag[0]:
                continue
            item = tag[0].split(',')
            for it in item:
                if it != '':
                    tag_list.append(it)
        return JsonResponse({'status': True, 'tag': list(set(tag_list))})


class SubmitCourseCover(View):
    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_cover = request.POST.get("course_cover")
        course_id = request.POST.get("course_id")
        # print(request.POST)
        # print(course_id, course_cover)
        print(course_id)
        if course_cover:
            course_info = Course.objects.all().filter(course_id=course_id).first()
            course_info.course_cover = course_cover
            course_info.save()
        else:
            return JsonResponse({"status": False, "message": "没有上传图片"})
        return JsonResponse({"status": True, "message": "封面添加完成"})


class GetCourseDetails(View):
    def get(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        course_id = request.GET.get('course_id')

        course = Course.objects.filter(course_id=course_id).first()
        if not course:
            return JsonResponse({'status': False, 'message': '课程不存在'})
        class_user = ClassUser.objects.filter(course_id=course_id, user_id=user_id).first()
        if class_user or course.course_creator==user_id:
            is_join = True
        else:
            is_join = False
        school = School.objects.filter(school_id=course.course_school).first()
        if not school:
            course_school = {
                'school_id': course.course_school,
                'school_name': '',
            }
        else:
            course_school = {
                'school_id': course.course_school,
                'school_name': school.school_name,
            }
        course_content = {
            'course_id': course.course_id,
            'course_title': course.course_name,
            'course_introduce': course.course_introduce,
            'course_cover': course.course_cover,
            'create_time': course.create_time,
            'course_cost': course.course_cost,
            'course_creator': course.course_creator,
            'course_credits': course.course_credits,
            'course_school': course_school,
            'creator_name': course.creator_name,
            'course_status': course.course_status,
            'start_time': course.start_time,
            'end_time': course.end_time,
            'course_browse': course.course_browse,
            'course_peoples': course.course_peoples,
            'is_recommend': course.is_recommend,
            'is_join': is_join,
        }
        return JsonResponse({'status': True, 'message': course_content})

    def post(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        identity = User.objects.get(user_id=user_id).user_power
        if identity > 2:
            return JsonResponse({"status": False, "message": "由老师来创建班级"})
        course_id = request.POST.get("course_id")
        course_name = request.POST.get('course_name')
        course_introduce = request.POST.get('course_introduce')
        start_time = request.POST.get("start_time")
        end_time = request.POST.get("end_time")
        course_credits = request.POST.get("course_credits")
        course_cost = request.POST.get("course_cost")
        print(course_name, course_introduce, start_time, end_time, course_cost, course_credits)
        is_exist = Course.objects.all().filter(course_id=course_id).first()
        if start_time > end_time:
            return JsonResponse({"status": False, "message": "创建时间错误"})
        if not course_name:
            return JsonResponse({"status": False, "message": "数据不全"})

        if not is_exist:
            print(course_name)
            Course.objects.create(
                course_name=course_name,
                course_introduce=course_introduce,
                # course_cover="data:image/png;base64,"+course_cover,
                # course_cover=course_cover,
                create_time=timezone.now(),
                course_cost=course_cost,
                course_creator=user_id,
                course_credits=course_credits,
                creator_name=user_id,
                course_status=0,
                start_time=start_time,
                end_time=end_time,
            )
            # course_cover.close()
            course_new = Course.objects.all().filter(creator_name=user_id, course_name=course_name).first()
            CourseUser.objects.create(
                course_id=course_new.course_id,
                course_user=user_id,
                user_identity=0
            )
            Class.objects.create(
                class_name="默认班级",
                class_creator=user_id,
                create_time=timezone.now(),
                class_introduce="这只是一个默认班级，课程中默认的班级",
                class_note="属于课程id=" + str(course_new.course_id),
                class_type=2,
                course_id=int(course_new.course_id),
            )
            return JsonResponse({"status": True, "message": "修改成功", "course_id": course_new.course_id})
        else:
            print(is_exist.course_name)
            is_exist.course_name = course_name
            is_exist.course_introduce = course_introduce
            is_exist.course_credits = course_credits
            is_exist.course_cost = course_cost
            is_exist.start_time = start_time
            is_exist.end_time = end_time
            is_exist.save()
            course_new = Course.objects.all().filter(creator_name=user_id, course_name=course_name).first()
            return JsonResponse({"status": True, "message": "修改成功", "course_id": course_new.course_id})


    def put(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)

        if not user_id:
            return JsonResponse({"status": False, "message": "用户认证失败"})
        identity = User.objects.filter(user_id=user_id).first().user_power
        if identity > 2:
            return JsonResponse({"status": False, "message": "你的等级不够"})


    def delete(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        course_id = request.GET.get("course_id")
        print(course_id)
        if not user_id:
            return JsonResponse({'status': False, "message": "用户认证失败"})
        user = User.objects.filter(user_id=user_id,).first()
        if not user:
            return JsonResponse({'status': False, 'message': '用户未完成信息'})
        course = Course.objects.filter(course_id=course_id).first()
        if not course:
            return JsonResponse({"status": False, "message": "不存在该课程"})
        if user.user_power >= 2 and course.course_creator == user_id:
            return JsonResponse({"status": False, 'message': "你没有权限，请联系管理员！"})
        course.is_delete = True
        course.is_show = False
        course.save()
        # Chapter.objects.filter(course_id=course_id).delete()
        # ChapterContent.objects.filter(course_id=course_id).delete()
        # CourseUser.objects.filter(course_id=course_id).delete()
        # GradeWeights.objects.filter(course_id=course_id).delete()
        # all_class = Class.objects.filter(course_id=course_id)
        # for the_class in all_class:
        #     ClassUser.objects.filter(class_id=the_class.class_id).delete()
        #     ChapterClass.objects.filter(class_id=the_class.class_id).delete()
        #     ChapterUser.objects.filter(class_id=the_class.class_id).delete()
        #     the_class.delete()
        # tasks = Task.objects.filter(task_course=course_id)
        # for task in tasks:
        #     TaskQuestion.objects.filter(task_id=task.task_id).delete()
        #     task.delete()
        # TaskUser.objects.filter(task_course=course_id).delete()
        # TaskSubmit.objects.filter(task_course=course_id).delete()
        # course.delete()
        return JsonResponse({'status': True, 'message': '删除成功'})



class CourseWeights(View):
    """
    获取/修改 课程各类分数所占的权重
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_id = request.GET.get("course_id")
        weight = GradeWeights.objects.filter(course_id=course_id).first()
        grade_wights = []
        grade_wights.append({
            "chapter_radio": weight.chapter_ratio,
            "discussion_sum": weight.discussion_ratio,
            "discussion_ratio": weight.discussion_ratio,
            "work_ratio": weight.work_ratio,
            "exam_ratio": weight.exam_ratio
        })
        return JsonResponse({"status": True, "message": grade_wights})

    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        chapter_radio = request.POST.get("chapter_radio")
        discuss_sum = request.POST.get("discuss_sun")
        discuss_ratio = request.POST.get("discuss_ratio")
        work_ratio = request.POST.get("work_ratio")
        exam_ratio = request.POST.get("exam_ratio")
        course_id = request.POST.get("course_id")
        print(chapter_radio, discuss_sum, discuss_ratio,
              work_ratio, exam_ratio, course_id)
        grade_weight = GradeWeights.objects.filter(course_id=course_id)
        if not grade_weight:
            grade_weight.create(
                course_id=course_id,
                chapter_ratio=chapter_radio,
                discussion_num=discuss_sum,
                discussion_ratio=discuss_ratio,
                work_ratio=work_ratio,
                exam_ratio=exam_ratio
            )
            return JsonResponse({"status": True, "message": "课程成绩权重创建成功"})
        else:
            grade_weight = grade_weight.first()
            grade_weight.chapter_ratio = chapter_radio
            grade_weight.discussion_ratio = discuss_ratio
            grade_weight.discussion_num = discuss_sum
            grade_weight.work_ratio = work_ratio
            grade_weight.exam_ratio = work_ratio
            grade_weight.save()
            return JsonResponse({"status": True, "message": "课程成绩修改成功"})


class CourseChapter(View):
    """
    模块: 查看课程章节
    接口信息:
        GET:
            token:token认证
            user_id:用户账号
            course_id:课程编号
        POST:
            massage:课程章节
    """
    def get(self, request):
        course_id = request.GET.get('course_id')
        class_id = request.GET.get('class_id')
        if not course_id:
            return JsonResponse({'status': False, 'message': '课程不存在'})
        if class_id:
            chapter_class = ChapterClass.objects.filter(class_id=class_id)
            all_user = ChapterUser.objects.filter(class_id=class_id)
            user_num = ClassUser.objects.filter(class_id=class_id).count()
        print(course_id)
        all_chapter = Chapter.objects.filter(course_id=course_id)
        chapters = all_chapter.filter(chapter_grade=0)
        all_content = ChapterContent.objects.filter(course_id=course_id)
        chapter_list = []
        for chapter in chapters:
            sections = all_chapter.filter(pre_chapter=chapter.chapter_id, chapter_grade=1)
            section_list = []
            chapter_finish = 0
            section_num = sections.count()
            for section in sections:
                chapter_free = ""
                section_finish = 0
                if class_id:
                    the_class = chapter_class.filter(chapter_id=section.chapter_id).first()
                    if not the_class:
                        chapter_free = {
                            'chapter_status': 0,
                            'start_time': '',
                            'end_time': '',
                        }
                    else:
                        chapter_free = {
                            'chapter_status': 0,
                            'start_time': the_class.start_time,
                            'end_time': the_class.end_time,
                        }
                    learn_num = all_user.filter(chapter_id=section.chapter_id).count()
                    if user_num == 0:
                        section_finish = 0
                    else:
                        section_finish = int((learn_num / user_num) * 100)
                        chapter_finish += section_finish
                # contents = ChapterContent.objects.filter(chapter_id=section.chapter_id)
                contents = all_content.filter(chapter_id=section.chapter_id)
                if contents.exists():
                    content_list = json.loads(contents.first().chapter_content)
                else:
                    content_list = []
                # for content in contents:
                #     content_list.append({
                #         'chapter_content_id': content.chapter_content_id,
                #         'chapter_id': content.chapter_id,
                #         # 'course_id': content.course_id,
                #         # 'content_title': content.chapter_content_title,
                #         # 'chapter_type': content.chapter_type,
                #         'chapter_content': content.chapter_content
                #     })

                section_list.append({
                    'chapter_id': section.chapter_id,
                    'course_id': section.course_id,
                    'chapter_title': section.chapter_title,
                    'chapter_grade': section.chapter_grade,
                    'pre_chapter': section.pre_chapter,
                    'chapter_status': section.chapter_states,
                    'chapter_free': chapter_free,
                    'chapter_finish': section_finish,
                    'content_list': content_list,
                })
            if section_num == 0:
                chapter_finish = 0
            else:
                chapter_finish = int(chapter_finish / section_num)
            chapter_list.append({
                'chapter_id': chapter.chapter_id,
                'course_id': chapter.course_id,
                'chapter_title': chapter.chapter_title,
                'chapter_grade': chapter.chapter_grade,
                'pre_chapter': chapter.pre_chapter,
                'chapter_status': chapter.chapter_states,
                'section_list': section_list,
                'chapter_finish': chapter_finish,
            })
        return JsonResponse({'status': True, 'message': chapter_list})

    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户登录失败"})
        course_id = request.POST.get("course_id")
        chapter_title = request.POST.get("chapter_title")
        pre_chapter = request.POST.get("pre_chapter")

        if pre_chapter:
            chapter_grade = 1
        else:
            chapter_grade = 0
            pre_chapter = None
        Chapter.objects.create(
            course_id=course_id,
            chapter_title=chapter_title,
            chapter_grade=chapter_grade,
            pre_chapter=pre_chapter,
            create_time=timezone.now(),
        )
        return JsonResponse({"status": True, "message": "创建成功"})

    def delete(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户登录失败"})
        chapter_id = request.GET.get("chapter_id")
        chapter = Chapter.objects.filter(chapter_id=chapter_id).first()
        if not chapter:
            return JsonResponse({'status': False, 'message': '章节不存在'})
        if not chapter.pre_chapter:
            Chapter.objects.filter(pre_chapter=chapter.chapter_id).delete()
        chapter.delete()
        return JsonResponse({'status': True, 'message': '删除成功'})

class ChapterOpen(View):
    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        class_id = request.POST.get('class_id')
        course_id = request.POST.get('course_id')
        chapter_id = request.POST.get('chapter_id')
        chapter_status = request.POST.get('chapter_status')
        start_time = request.POST.get('start_time')
        end_time = request.POST.get('end_time')
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        chapter = ChapterClass.objects.filter(chapter_id=chapter_id, class_id=class_id).first()
        if chapter:
            chapter.chapter_status = chapter_status,
            chapter.start_time = start_time,
            chapter.end_time = end_time,
            chapter.save()
        else:
            ChapterClass.objects.create(
                chapter_id=chapter_id,
                class_id=class_id,
                course_id=course_id,
                chapter_status=chapter_status,
                start_time=start_time,
                end_time=end_time,
            )
        return JsonResponse({'status': True, 'message': '修改成功'})


class CourseAllExercises(View):
    """
    获取课程下所有的题目
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_id = request.GET.get("course_id")
        question_type = request.GET.get("question_type")
        text = request.GET.get("text")
        page = request.GET.get("page")
        total = request.GET.get("total")
        print("course_id", course_id, "question_type", question_type, "text",
              text, "page", page, "total", total, "get")
        if course_id == "NaN":
            course_id = None
        questions = Question.objects.filter(question_course=course_id,
                                            question_description__contains=text)
        # if total != '0':
        #     questions = questions[(int(page) - 1) * int(total): int(page) * int(total)]
        question_info = []
        for question in questions:
            user = User.objects.filter(user_id=question.upload_user).first()
            question_info.append({
                "question_id": question.question_id,
                "question_description": question.question_description,
                "question_type": question.question_type,
                "question_difficulty": question.question_difficulty,
                "question_tag": question.question_tag,
                "question_user": user.user_name,
                "upload_time": question.upload_time
            })
        return JsonResponse({"status": True, "message": question_info})

    # def delete(self, request):
        # token = request.COOKIES.get("token")
        # user_id = cache.get(token)
        # if not user_id:
        #     return JsonResponse({"status": False, "message": "用户未登录"})
        # question_id = request.GET.get("question_id")
        # print(question_id, "delete")
        # question = Question.objects.filter(question_id=question_id).first()
        # if question:
        #     question.delete()
        #     return JsonResponse({"status": True, "message": "删除成功"})
        # else:
        #     return JsonResponse({"status": False, "message": "没有这个问题"})


class DeleteQuestion(View):
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        question_id = request.GET.get("question_id")
        print(question_id, "delete")
        question = Question.objects.filter(question_id=question_id).first()
        if question:
            question.delete()
            return JsonResponse({"status": True, "message": "删除成功"})
        else:
            return JsonResponse({"status": False, "message": "没有这个问题"})


class CreateTask(View):
    """
    往题库里面添加题目
    """
    def get(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        task_id = request.GET.get('task_id')
        submit_id = request.GET.get('submit_id')
        is_see = request.GET.get('is_see')
        if not user_id:
            return JsonResponse({'status': False, 'message': '用户未登录'})
        if is_see == 'true':
            is_see = True
        elif is_see == 'false':
            is_see = False
        else:
            return JsonResponse({'status': False, 'message': '预览方式错误'})
        task = Task.objects.filter(task_id=task_id).first()
        if not task:
            return JsonResponse({'status': False, 'message': '作业/考试不存在'})
        if submit_id:
            task_submit = TaskSubmit.objects.filter(submit_id=submit_id).first()
            if not task_submit:
                return JsonResponse({'status': False, 'message': '提交不存在'})
            submit_content = {
                'submit_id': task_submit.submit_id,
                'task_id': task_submit.task_id,
                'task_user': task_submit.task_user,
                'task_class': task_submit.task_class,
                'create_time': task_submit.create_time,
                'submit_content': task.submit_content,
                'submit_score': task.submit_score,
            }
            return JsonResponse({'status': True, 'message': submit_content})
        task_user = TaskUser.objects.filter(task_id=task_id).first()
        task_questions = TaskQuestion.objects.filter(task_id=task_id).order_by('question_number')
        questions = Question.objects.all()
        question_list = []
        for task_question in task_questions:
            question = questions.filter(question_id=task_question.question_id).first()
            if not question:
                continue
            if question.question_type in [0, 1, 3]:
                question_option = eval(question.question_option)
            else:
                question_option = question.question_option
            question_list.append({
                'question_id': question.question_id,
                'question_description': question.question_description,
                'question_type': question.question_type,
                'question_option': question_option,
                'choice_answer': question.choice_answer,
                'question_explanation': question.question_explanation,
                'question_difficulty': question.question_difficulty,
                'question_tag': question.question_tag,
                'question_score': task_question.question_score,
            })
        if is_see:
            task_content = {
                'task_id': task.task_id,
                'task_title': task.task_title,
                'task_explain': task.task_explain,
                'task_creator': task.task_creator,
                'creator_name': task.creator_name,
                'create_time': task.create_time,
                'total_score': task.total_score,
                'task_type': task.task_type,
                'question_list': question_list,
            }
        else:
            task_content = {
                'task_id': task.task_id,
                'task_title': task.task_title,
                'task_explain': task.task_explain,
                'task_creator': task_user.task_creator,
                'creator_name': task_user.creator_name,
                'create_time': task.create_time,
                'total_score': task.total_score,
                'task_type': task.task_type,
                'begin_time': task_user.begin_time,
                'end_time': task_user.end_time,
                'task_judge': task_user.task_judge,
                'answer_time': task_user.answer_time,
                'question_list': question_list,
            }
        return JsonResponse({'status': True, 'message': task_content})

    def post(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        course_id = request.POST.get('course_id')
        task_title = request.POST.get('task_title')
        task_type = request.POST.get('task_type')
        total_score = request.POST.get('total_score')
        problem_list = json.loads(request.POST.get('problem_content'))
        print(task_title, task_type, problem_list)
        if not task_title:
            return JsonResponse({'status': False, 'message': '任务没有标题'})
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        user = User.objects.filter(user_id=user_id).first()
        course = Course.objects.filter(course_id=course_id).first()
        if not course:
            return JsonResponse({'status': False, 'message': '课程不存在'})
        task = Task.objects.create(
            task_title=task_title,
            task_creator=user_id,
            creator_name=user.user_name,
            create_time=timezone.now(),
            total_score=total_score,
            task_type=task_type,
            task_course=course_id,
        )
        question_num = 0
        for problem in problem_list:
            question = Question.objects.create(
                question_description=problem['title'],
                question_type=problem['type'],
                question_option=problem['answer'],
                choice_answer=problem['choice_answer'],
                question_explanation=problem['answer_analyze'],
                question_difficulty=problem['degree'],
                question_tag=problem['knowledge_point'],
                question_course=course_id,
                upload_user=user_id,
                upload_time=timezone.now(),
            )
            TaskQuestion.objects.create(
                task_id=task.task_id,
                question_id=question.question_id,
                question_number=question_num,
                question_score=problem['score'],
            )
            question_num += 1
        return JsonResponse({'status': True, 'message': '任务创建成功'})


class SubmitTask(View):
    def post(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登入'})
        release_id = request.POST.get('release_id')
        submit_id = request.POST.get('submit_id')
        submit_ip = publicMethod.get_ip(request)
        task_id = request.POST.get('task_id')
        submit_score = request.POST.get('user_score')
        submit_content = json.loads(request.POST.get('problem_content'))
        task = Task.objects.filter(task_id=task_id).first()
        if not task:
            return JsonResponse({'status': False, 'message': '任务不存在'})
        if submit_id:
            task_submit = TaskSubmit.objects.filter(submit_id).first()
            task_submit.submit_content = submit_content
            task_submit.submit_score = submit_score
            task_submit.judge_time = timezone.now()
            task_submit.judge_user = user_id
            task_submit.save()
            return JsonResponse({'status': True, 'message': '判题成功'})
        TaskSubmit.objects.create(
            task_id=task_id,
            release_id=release_id,
            task_user=user_id,
            task_course=task.task_course,
            create_time=timezone.now(),
            submit_content=submit_content,
            submit_score=submit_score,
            submit_ip=submit_ip,
        )
        return JsonResponse({'status': True, 'message': '提交成功'})


class AddCourseMenu(View):
    """
    模块: 查看资料/新建文件夹
    接口信息:
    GET:
        course_id: 课程ID
        pre_menu: 前置文件夹ID
    POST:
        token: token认证
        course_id: 课程ID
        pre_menu: 前置文件夹ID
        menu_name: 文件夹名字
    """
    def get(self, request):
        course_id = request.GET.get('course_id')
        pre_menu = request.GET.get('pre_menu')
        menu_type = request.GET.get('menu_type')

        if not course_id:
            massage = {'err': '信息不完全'}
            return JsonResponse(massage, safe=False)

        menus = CourseMenu.objects.filter(course_id=course_id, pre_menu=pre_menu, menu_type=menu_type).order_by('menu_number')
        files = CourseFile.objects.filter(course_id=course_id, file_menu=pre_menu)

        menus_data = []
        files_data = []

        for menu in menus:
            menus_data.append({
                'menu_id': menu.menu_id,
                'course_id': menu.course_id,
                'menu_name': menu.menu_name,
                'pre_menu': menu.pre_menu,
            })

        for file in files:
            user = User.objects.filter(user_id=file.file_creator).first()
            files_data.append({
                'file_id': file.file_id,
                'course_id': file.course_id,
                'file_type': file.file_type,
                'file_name': file.file_name,
                'file_creator': file.file_creator,
                'file_creator_nick': user.user_nick,
                'file_menu': file.file_menu,
                # 'course_file': str(file.course_file),
            })

        massage = {'menus_data': menus_data, 'files_data': files_data}
        return JsonResponse(massage, safe=False)

    def post(self, request):
        token = request.POST.get('token')
        course_id = request.POST.get('course_id')
        pre_menu = request.POST.get('pre_menu')
        menu_name = request.POST.get('menu_name')
        menu_type = request.POST.get('menu_type')

        if not (token and course_id and menu_name and menu_type):
            massage = {'err': '信息不完全'}
            return JsonResponse(massage, safe=False)

        user_id = publicMethod.check_user_login(token)
        if not user_id:
            return JsonResponse({'err': '未登录'}, safe=False)
        else:
            user = User.objects.filter(user_id=user_id).first()
            if not user:
                return JsonResponse({'err': '用户不存在or用户信息未完善'}, safe=False)

        users = CourseUser.objects.filter(course_id=course_id, course_user=user_id).first()
        if not users:
            massage = {'err': '无权限'}
            return JsonResponse(massage, safe=False)

        CourseMenu.objects.create(
            course_id=course_id,
            menu_name=menu_name,
            menu_number='0',
            pre_menu=pre_menu,
            menu_status='0',
            menu_type=menu_type
        )

        massage = {'massage': '创建成功'}
        return JsonResponse(massage, safe=False)


class Settlement(View):
    """
    模块：查看课程结算信息
    接口信息：
        get:

    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        # 权限认证
        identity = User.objects.filter(user_id=user_id).first().user_power
        info = []
        course_id = request.GET.get("course_id")
        class_id = request.GET.get("class_id")
        student_id = request.GET.get("student_id")
        print(course_id, class_id, student_id, user_id)
        all_user = User.objects.all()
        if identity <= 2:
            print("老师或者是管理员")
            my_students = ClassUser.objects.filter(course_id=course_id, user_type=0)
            if class_id:
                my_students = my_students.filter(class_id=class_id)
            total = my_students.count()
            for my_student in my_students:
                chapter = ChapterUser.objects.filter(user_id=my_student.user_id)
                total_chapter = chapter.count()
                study_chapter = chapter.filter(status=1).count()
                forum = Forum.objects.filter(forum_creator=my_student.user_id, forum_status=1)
                print(my_student.user_id)
                name = all_user.filter(user_id=my_student.user_id).first()
                print(name)
                info.append({
                    "user_id": my_student.user_id,
                    "user_name": name.user_name,
                    "discuss": forum.count(),
                    "class": Class.objects.filter(class_id=class_id).first().class_name,
                    "doneChapter": ""+str(study_chapter)+"/"+str(total_chapter)
                })
            return JsonResponse({"status": True, "message": info, "total": total})
        else:
            chapter = ChapterUser.objects.filter(user_id=user_id)
            total_chapter = chapter.count()
            study_chapter = chapter.filter(status=1).count()
            forum = Forum.objects.filter(forum_creator=user_id, forum_status=1)
            name = User.objects.filter(user_id=user_id).first()
            if not name:
                name = ''
            else:
                name = name.user_name
            info.append({
                "user_id": user_id,
                "user_name": name,
                "discuss": forum.count(),
                "doneChapter": "" + str(study_chapter) + "/" + str(total_chapter)
            })
            return JsonResponse({"status": True, "message": info})


class CourseManage(View):
    """
    模块:获取课程管理信息
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        page = request.GET.get('page')
        total = request.GET.get('total')
        text = request.GET.get('text')
        print(page, total, text)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'status': False, 'message': "信息未完善"})
        if user.user_power >= 2:
            return JsonResponse({'status': False, 'message': "无权限"})
        course_list = []
        all_course = Course.objects.filter(is_delete=False)
        if user.user_power == 2:
            all_course = all_course.filter(course_creator=user_id)
        if text:
            all_course = all_course.filter(Q(course_name__contains=text) | Q(creator_name__contains=text))
        course_num = all_course.count()
        if total != '0':
            all_course = all_course[(int(page) - 1) * int(total): int(page) * int(total)]
        for course in all_course:
            course_list.append({
                "course_id": course.course_id,
                "course_name": course.course_name,
                "course_teacher": course.creator_name,
                "course_school": course.course_school,
                "course_credit": course.course_credits,
                "create_time": course.create_time,
                "start_time": course.start_time,
                "end_time": course.end_time,
                "is_show": course.is_show,
            })
        return JsonResponse({"status": True, "message": course_list, 'total': course_num})

    def put(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'status': False, 'message': "信息未完善"})
        if user.user_power >= 2:
            return JsonResponse({'status': False, 'message': "无权限"})
        course_id = request.GET.get('course_id')
        course = Course.objects.filter(course_id=course_id).first()
        if not course:
            return JsonResponse({'status': False, 'message': '课程不存在'})
        course.is_show = not course.is_show
        course.save()
        return JsonResponse({'status': True, 'message': '修改成功'})


class ChapterContentData(View):
    """
    章节内容模块:
        get:获取课程下所有课程资源
        post:将课程资源放入章节
    """
    def get(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        course_id = request.GET.get("course_id")
        text = request.GET.get('text')
        print(course_id, text)
        if course_id == "NaN":
            course_id = None
        all_files = CourseFile.objects.filter(course_id=course_id, file_status=0)
        if text:
            all_files = all_files.filter(file_name__contains=text)
        users = User.objects.all()
        info = []
        for file in all_files:
            user = users.filter(user_id=file.file_creator).first()
            if user:
                user_name = user.user_name
            else:
                user_name = file.file_creator
            path = os.path.join(settings.MEDIA_URL, 'icon.jpg')
            size = os.path.getsize(path)
            size = size/1024
            info.append({
                "file_id": file.file_id,
                "file_name": file.file_name,
                "create_time": file.upload_time,
                "user_name": user_name,
                "size": "{:.2f}kb".format(size)
            })
        return JsonResponse({"status": True, "message": info})

    def post(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        chapter_id = request.POST.get("chapter_id")
        course_id = request.POST.get("course_id")
        chapter_content = request.POST.get('chapter_content')

        # print(chapter_id, chapter_content)
        content = ChapterContent.objects.filter(chapter_id=chapter_id).first()
        if content:
            content.chapter_content = chapter_content
            content.save()
        else:
            ChapterContent.objects.create(
                course_id=course_id,
                chapter_id=chapter_id,
                create_time=timezone.now(),
                chapter_creator=user_id,
                chapter_content=chapter_content,
            )
        return JsonResponse({"status": True, "message": "添加成功"})

    def put(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        chapter_content_id = request.GET.get('content_id')
        content = ChapterContent.objects.filter(chapter_content_id=chapter_content_id).first()
        if not content:
            return JsonResponse({'status': False, 'message': '内容不存在'})
        chapter_type = request.GET.get('chapter_type')
        chapter_content = request.GET.get('chapter_content')
        content.chapter_type = chapter_type
        content.chapter_content = chapter_content
        content.save()
        return JsonResponse({'status': True, 'message': '保存成功'})

    def delete(self, request):
        token = request.COOKIES.get("token")
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({"status": False, "message": "用户未登录"})
        chapter_content_id = request.GET.get('content_id')
        content = ChapterContent.objects.filter(chapter_content_id=chapter_content_id).first()
        if not content:
            return JsonResponse({'status': False, 'message': '内容不存在'})
        content.delete()
        return JsonResponse({'status': True, 'message': '删除成功'})


class VideoPlayer(View):
    def file_iterator(self, fileName, chunk_size=8192, offset=0, length=None):
        with open(fileName, "rb") as f:
            f.seek(offset, os.SEEK_SET)
            remaining = length
            while True:
                # bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
                bytes_length = chunk_size if remaining is None else min(remaining, chunk_size)
                data = f.read(bytes_length)
                if not data:
                    break
                if remaining:
                    remaining -= len(data)
                yield data

    def get(self, request):
        # course_id = request.GET.get("course_id")
        # chapter_id = request.GET.get("chapter_id")
        # file_id = request.GET.get("file_id")
        # print(course_id, chapter_id)
        # chapter = Chapter.objects.filter(course_id=course_id, chapter_id=chapter_id).first()
        # print(chapter.chapter_id)
        # content = ChapterContent.objects.filter(course_id=course_id, chapter_id=chapter_id,
        #                                         chapter_content=file_id).first().chapter_content
        # path = CourseFile.objects.filter(course_id=course_id, file_id=content).first().course_file
        # print(path)
        """将视频文件以流媒体的方式响应"""
        range_header = request.META.get('HTTP_RANGE', '').strip()
        range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
        range_match = range_re.match(range_header)
        if range_match:
            path = "course_file/5/2/6DF0470F330224A02FD19D154A374ECC.mp4"
        else:
            path = "course_file/5/0/pdf1.pdf"
        path = os.path.join(settings.MEDIA_URL, str(path))
        size = os.path.getsize(path)
        content_type, encoding = mimetypes.guess_type(path)
        content_type = content_type or 'application/octet-stream'
        if range_match:
            first_byte, last_byte = range_match.groups()
            first_byte = int(first_byte) if first_byte else 0
            last_byte = first_byte + 1024 * 1024 * 8  # 8M 每片,响应体最大体积
            if last_byte >= size:
                last_byte = size - 1
            length = last_byte - first_byte + 1
            print(type(path))
            resp = StreamingHttpResponse(self.file_iterator(fileName=path, offset=first_byte, length=length),
                                         status=206, content_type=content_type)
            print(path)
            resp['Content-Length'] = str(length)
            resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, size)
        else:
            # 不是以视频流方式的获取时，以生成器方式返回整个文件，节省内存
            print(content_type)
            resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')), content_type=content_type)
            resp['Content-Length'] = str(size)
            resp['Content-Disposition'] = "filename="+"b1.pdf"
        resp['Accept-Ranges'] = 'bytes'
        return resp

class Upload(View):
    def get(self, request):
        file_id = request.GET.get('file_id')
        course_file = CourseFile.objects.filter(file_id=file_id).first()
        if not course_file:
            return JsonResponse({'status': False, 'message': '文件不存在'})
        path = os.path.join(settings.MEDIA_URL, str(course_file.course_file))
        resp = StreamingHttpResponse(VideoPlayer().file_iterator(path))
        resp['Content-Type'] = 'application/octet-stream'
        return resp

    def patch(self, request):
        file_id = request.GET.get("file_id")
        course_file = CourseFile.objects.filter(file_id=file_id).first()
        if not course_file:
            return JsonResponse({"message": "没有这个文件"})
        return JsonResponse({'status': True, "message": course_file.file_name})

    def post(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        # num = request.POST.get("num")
        # total_length = request.POST.get("totalLength")
        chunk = request.FILES.get("file")
        course_id = request.POST.get("course_id")
        if course_id:
            course = Course.objects.filter(course_id=course_id).first()
            if not course:
                return JsonResponse({'status': False, 'message': '课程不存在'})
        else:
            return JsonResponse({'status': False, 'message': '课程编号未传'})
        # offset = num*1024*1024*2
        file_type = chunk.name.split('.')[1]
        file_path = "course_file/"
        audio_list = ['cda', 'wav', 'mp3', 'aif', 'aiff', 'mid', 'wma', 'ra', 'vqf', 'ape']
        video_list = ['wmv', 'asf', 'asx', 'rm', 'rmvb', 'mpg', 'mpeg', 'mpe', '3gp', 'mov', 'mp4', 'm4v', 'avi', 'dat',
                      'mkv', 'flv', 'vob']
        image_list = ['psd', 'pdd', 'gif', 'jpeg', 'png', 'pdf', 'bmp', 'jpg']
        if file_type in audio_list:
            file_path = file_path+str(course_id)+'/1/'
        elif file_type in video_list:
            file_path = file_path+str(course_id)+'/2/'
        elif file_type in image_list:
            file_path = file_path+str(course_id)+'/3/'
        else:
            file_path = file_path + str(course_id) + '/0/'
        print(chunk.name, course_id, file_type, file_path)
        path = os.path.join(settings.MEDIA_URL, file_path)
        re_path = path.strip()
        path += chunk.name
        is_exist = CourseFile.objects.filter(course_file=path)
        print(is_exist)
        re_path = re_path.rstrip('/')
        print(re_path)
        path_exist = os.path.exists(re_path)
        if not path_exist:
            os.makedirs(re_path)
        else:
            print("路径已存在")
        if not is_exist:
            print(path)
            with open(path, "wb") as f:
                # f.seek(offset, os.SEEK_SET)
                for i in chunk:
                    f.write(i)
            f.close()
            file_path += chunk.name
            CourseFile.objects.create(
                course_id=course_id,
                file_type=0,
                file_name=chunk.name,
                upload_time=timezone.now(),
                file_creator=user_id,
                course_file=file_path,
            )
            return JsonResponse({"status": True, 'message': '上传成功'})
        else:
            return JsonResponse({"status": True, 'message': '课程资料已存在'})

    def delete(self, request):
        token = request.COOKIES.get('token')
        user_id = cache.get(token)
        if not user_id:
            return JsonResponse({'status': False, 'message': '未登录'})
        file_id = request.GET.get("file_id")
        print(file_id)
        if file_id:
            file = CourseFile.objects.filter(file_id=file_id).first()
            path = str(file.course_file)
            file_path = os.path.join(settings.MEDIA_URL, path)
            os.remove(file_path)
            file.delete()
            return JsonResponse({"status": True, "message": "删除成功"})
        else:
            return JsonResponse({"status": False, "message": "删除失败"})

